package comtgl.demo.utils;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

public class SignatureUtils {

    public static String generate(Map<String, String> params, String appSecret) {
        // 1. 过滤空值并排序
        List<String> keys = params.keySet().stream()
                .filter(k -> !k.equals("sign") && params.get(k) != null)
                .sorted()
                .collect(Collectors.toList());

        // 2. 拼接参数
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);

        // 3. 拼接密钥
        String data = sb + "&secret=" + appSecret;

        // 4. HMAC-SHA256加密
        try {
            Mac sha256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new  SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256.init(secretKey);
            byte[] bytes = sha256.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Hex.encodeHexString(bytes);
        } catch (Exception e) {
            throw new RuntimeException("签名生成失败", e);
        }
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("appKey", "6086b395");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("nonce", UUID.randomUUID().toString());

        // 生成签名
        String sign = SignatureUtils.generate(params, "79a151dd-2187-4699-9310-bd4643528c45");
        params.put("sign", sign);

        params.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}